<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in ncpsy_product_variety"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作物昵称" prop="cropName">
        <el-input
          v-model="queryParams.cropName"
          placeholder="请输入作物昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ncpsy:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ncpsy:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ncpsy:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ncpsy:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作物ID" align="center" prop="cropId" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="ncpsy_product_variety" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="计划开始时间" align="center" prop="beginTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="reapTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reapTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作物昵称" align="center" prop="cropName" />
      <el-table-column label="交易哈希" align="center" prop="hash" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ncpsy:product:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ncpsy:product:remove']">删除</el-button>
          <el-button link type="primary" icon="" @click="handle(scope.row)" v-hasPermi="['ncpsy:product:remove']">事件详情</el-button>
          <el-button link type="primary" icon="" @click="handledata(scope.row)" v-hasPermi="['ncpsy:product:remove']">产品详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改农产品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品ID" />
        </el-form-item>
        <el-form-item label="产地ID" prop="areaId">
          <el-input v-model="form.areaId" placeholder="请输入产地ID" />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in ncpsy_product_variety"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="beginTime">
          <el-date-picker clearable
            v-model="form.beginTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="reapTime">
          <el-date-picker clearable
            v-model="form.reapTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="作物昵称" prop="cropName">
          <el-input v-model="form.cropName" placeholder="请输入作物昵称" />
        </el-form-item>
        <el-form-item label="预计总产量" prop="estimatedTotalYield">
          <el-input v-model="form.estimatedTotalYield" placeholder="请输入预计总产量" />
        </el-form-item>
        <el-form-item label="实际总产量" prop="totalYield">
          <el-input v-model="form.totalYield" placeholder="请输入实际总产量" />
        </el-form-item>
        <el-form-item label="产量单位" prop="yieldUnit">
          <el-select v-model="form.yieldUnit" placeholder="请选择产量单位">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="种植面积" prop="plantingAravage">
          <el-input v-model="form.plantingAravage" placeholder="请输入种植面积" />
        </el-form-item>
        <el-form-item label="交易哈希" prop="hash">
          <el-input v-model="form.hash" placeholder="请输入交易哈希" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="作物ID">{{ detailData.cropId }}</el-descriptions-item>
        <el-descriptions-item label="产品ID">{{ detailData.productId }}</el-descriptions-item>
        <el-descriptions-item label="产地ID">{{ detailData.areaId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailData.userId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="ncpsy_product_variety" :value="detailData.status" />
        </el-descriptions-item>
        <el-descriptions-item label="计划开始时间">{{ parseTime(detailData.beginTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="计划结束时间">{{ parseTime(detailData.reapTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="作物昵称">{{ detailData.cropName }}</el-descriptions-item>
        <el-descriptions-item label="预计总产量">{{ detailData.estimatedTotalYield }}</el-descriptions-item>
        <el-descriptions-item label="实际总产量">{{ detailData.totalYield }}</el-descriptions-item>
        <el-descriptions-item label="产量单位">{{ detailData.yieldUnit }}</el-descriptions-item>
        <el-descriptions-item label="种植面积">{{ detailData.plantingAravage }}</el-descriptions-item>
        <el-descriptions-item label="交易哈希">{{ detailData.hash }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailData.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ detailData.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailData.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/ncpsy/management/product"
import { useRouter } from 'vue-router'

const router = useRouter()
const { proxy } = getCurrentInstance()
const { ncpsy_product_variety, sys_yes_no } = proxy.useDict('ncpsy_product_variety', 'sys_yes_no')

const productList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const detailTitle = ref("")
const detailData = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    cropName: null,
  },
  rules: {
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    beginTime: [
      { required: true, message: "计划开始时间不能为空", trigger: "blur" }
    ],
    estimatedTotalYield: [
      { required: true, message: "预计总产量不能为空", trigger: "blur" }
    ],
    yieldUnit: [
      { required: true, message: "产量单位不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询农产品管理列表 */
function getList() {
  loading.value = true
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    cropId: null,
    productId: null,
    areaId: null,
    userId: null,
    status: null,
    beginTime: null,
    reapTime: null,
    cropName: null,
    estimatedTotalYield: null,
    totalYield: null,
    yieldUnit: null,
    plantingAravage: null,
    hash: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("productRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.cropId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加农产品管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _cropId = row.cropId || ids.value
  getProduct(_cropId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改农产品管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.cropId != null) {
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cropIds = row.cropId || ids.value
  proxy.$modal.confirm('是否确认删除农产品管理编号为"' + _cropIds + '"的数据项？').then(function() {
    return delProduct(_cropIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ncpsy/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}


/** 详情按钮操作，实现路由跳转 */
function handle(row) {
  const cropId = row.cropId
  router.push({
    path: '/farmerall/event',
    query: { cropId: cropId }
  })
}

/** 产品详情按钮操作 */
function handledata(row) {
  const _cropId = row.cropId
  getProduct(_cropId).then(response => {
    detailData.value = response.data
    detailTitle.value = "产品详情 - " + response.data.cropName
    detailOpen.value = true
  })
}

getList()
</script>
